<script setup lang="ts">
import { onActivated, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAppStore } from '@/store/modules/app'
import { getTask, getCardTab, getcardTabETC, addTaskMess, getSN } from '@/api/task'
import moment from 'moment'
import { showToast } from 'vant'
import { onMounted } from 'vue'
// import { isActiveList } from '@/utils/task'

const appStore = useAppStore()
const { back, push } = useRouter()
const userInfo = ref(appStore.getUserInfo)
const route = useRoute()
const onBack = () => {
  back()
}
const gotoHistory = () => {
  push({
    name: 'followHistory',
    query: {
      id: taskId.value
    }
  })
}
interface taskFormType {
  id: string
  staffId: string
  merPhone: string
  merName: string
  addressHead: string
  addressJd: string
  address: string
  remark: string
  machineSnCode: string
  callTime: string //上门时间
  addressHeadCode: string
  taskActive: string
  taskActiveText: string
  bankName: string
  isCall: string
  isCallText: string
  isActive: string
  isActiveText: string
  isUrgent: string
  isUrgentText: string
  taskRemark: string
  activateTime: string
  agentCode: string
  snCode: string
  vehicleName: string
  vehicleNumber: string
}

const taskId = ref('')
const taskData = ref<taskFormType>({
  id: '',
  staffId: '',
  merPhone: '',
  merName: '',
  addressHead: '',
  address: '',
  remark: '',
  machineSnCode: '',
  callTime: '',
  addressHeadCode: '',
  addressJd: '',
  taskActive: '',
  taskActiveText: '',
  bankName: '',
  isCall: '',
  isCallText: '',
  isActive: '',
  isActiveText: '',
  isUrgent: '',
  isUrgentText: '',
  taskRemark: '',
  activateTime: '',
  agentCode: '',
  snCode: '',
  vehicleName: '',
  vehicleNumber: ''
})
const search = () => {
  getTask({
    id: taskId.value
  }).then((res) => {
    taskData.value = res.data
    taskData.value.taskActiveText = getOptionText(taskData.value.taskActive, taskActiveList.value)
    taskData.value.snCode = taskData.value.machineSnCode
    snCode.value = [taskData.value.machineSnCode]
    taskActive.value = [taskData.value.taskActive]
    currentDate.value = moment(taskData.value.callTime ? taskData.value.callTime : new Date())
      .format('YYYY-MM-DD')
      .split('-') as []
    currentTime.value = moment(taskData.value.callTime ? taskData.value.callTime : new Date())
      .format('HH:mm')
      .split(':') as []

    if (taskData.value.taskActive) {
      let index = taskActiveList.value.findIndex((e) => {
        return e.value == taskData.value.taskActive
      })
      if (index > 0) {
        taskActiveList.value = taskActiveList.value.slice(
          index >= 2 ? 2 : index,
          taskActiveList.value.length
        )
      }
    }
    taskData.value.isCallText = getOptionText(taskData.value.isCall, isCallList)
    taskData.value.isActiveText = getOptionText(taskData.value.isActive, isActiveList)
    taskData.value.isUrgentText = getOptionText(taskData.value.isUrgent, isUrgentList)

    taskData.value.activateTime = moment(taskData.value.activateTime || new Date()).format(
      'YYYY-MM-DD'
    )
    activateTime.value = moment(taskData.value.activateTime || new Date())
      .format('YYYY-MM-DD')
      .split('-')
    getCardTabList()
  })
  getSN({
    userId: userInfo.value.id
  }).then((res) => {
    snList.value = res.data.list.map((e: any) => {
      return {
        text: e.sn_code,
        value: e.sn_code
      }
    })
  })
}
const snList = ref([])

onActivated(() => {
  userInfo.value = appStore.getUserInfo
  init()
})
onMounted(() => {
  init()
})
const init = () => {
  taskData.value = {
    id: '',
    staffId: '',
    merPhone: '',
    merName: '',
    addressHead: '',
    address: '',
    remark: '',
    machineSnCode: '',
    callTime: '',
    addressHeadCode: '',
    addressJd: '',
    taskActive: '',
    taskActiveText: '',
    bankName: '',
    isCall: '',
    isCallText: '',
    isActive: '',
    isActiveText: '',
    isUrgent: '',
    isUrgentText: '',
    taskRemark: '',
    activateTime: '',
    agentCode: '',
    snCode: '',
    vehicleName: '',
    vehicleNumber: ''
  }
  taskActiveList.value = [
    {
      text: '新客户',
      value: '0'
    },
    {
      text: '待回访',
      value: '1'
    },
    {
      text: '可上门',
      value: '4'
    },
    {
      text: '已上门',
      value: '5'
    },
    {
      text: '无意向',
      value: '6'
    },
    {
      text: '未接通',
      value: '3'
    }
  ]
  const { id } = route.query
  taskId.value = id as string
  search()
}
const callPhone = () => {
  window.location.href = `tel:${taskData.value.merPhone}`
}

const cardTabList = ref([])
const getCardTabList = () => {
  if (taskData.value.agentCode == 'agent_etc') {
    getcardTabETC().then((res) => {
      cardTabList.value = res.data.map((e: any) => {
        return {
          text: e.name,
          ...e
        }
      })
    })
  } else {
    getCardTab().then((res) => {
      cardTabList.value = res.data.map((e: any) => {
        return {
          text: e.name,
          ...e
        }
      })
    })
  }
}

const onSubmit = (values: any) => {
  addTaskMess({
    userId: userInfo.value.id,
    ...taskData.value
  }).then((res) => {
    if (res.success) {
      const listPage = route.query.name?.toString() || ''
      let pageData = appStore.getPageData(listPage)
      if (pageData) {
        let content = pageData.content as any[]
        console.log(content)
        let index = content.findIndex((e: any) => {
          return e.id == taskData.value.id
        })
        content[index] = taskData.value
        appStore.setPageData(listPage, {
          ...pageData,
          content
        })
      }

      showToast(res.message)
      onBack()
    }
  })
}
const taskActive = ref([taskData.value.taskActive])
const taskActiveList = ref([
  {
    text: '新客户',
    value: '0'
  },
  {
    text: '待回访',
    value: '1'
  },
  {
    text: '可上门',
    value: '4'
  },
  {
    text: '已上门',
    value: '5'
  },
  {
    text: '无意向',
    value: '6'
  },
  {
    text: '未接通',
    value: '3'
  }
])
const showTaskActivePicker = ref(false)
const confirmTaskActive = (val: any) => {
  console.log(val)
  const select = val.selectedOptions[0]
  taskData.value.taskActive = select.value
  taskData.value.taskActiveText = select.text
  showTaskActivePicker.value = false
}
const getOptionText = (val: any, list: any) => {
  let item = list.find((e: any) => {
    return e.value == val
  })
  return item ? item.text : ''
}

const showTimePicker = ref(false)
const currentDate = ref<string[]>([])
const currentTime = ref<string[]>([])

const confirmTime = () => {
  showTimePicker.value = false
  const val = `${currentDate.value.toString().replace(/,/g, '/')} ${currentTime.value
    .toString()
    .replace(/,/g, ':')} `
  taskData.value.callTime = moment(val).format('YYYY-MM-DD HH:mm')
}
const isCallList = [
  {
    text: '正常',
    value: '0'
  },
  {
    text: '急需处理',
    value: '1'
  },
  {
    text: '已超时',
    value: '2'
  }
]
const isActivePickerShow = ref(false)
const isActiveList = [
  {
    text: '未成交',
    value: '0'
  },
  {
    text: '待成交',
    value: '1'
  },
  {
    text: '已成交',
    value: '2'
  },
  {
    text: '需注销',
    value: '3'
  }
]
const isActive = ref([])
const confirmIsActive = (val: any) => {
  const select = val.selectedOptions[0]
  taskData.value.isActive = select.value
  taskData.value.isActiveText = select.text
  isActivePickerShow.value = false
}
const isUrgentList = [
  {
    text: '普通',
    value: '0'
  },
  {
    text: '加急',
    value: '1'
  },
  {
    text: '当日加急',
    value: '2'
  }
]
const showActivateTimePicker = ref(false)
const activateTime = ref<string[]>([])

const confirmActivateTime = (val: any) => {
  taskData.value.activateTime = moment(val.selectedValues.toString().replace(/,/g, '/')).format(
    'YYYY-MM-DD'
  )
  showActivateTimePicker.value = false
}

const showTaskRemark = ref(false)
const confirmTaskRemark = (val: any) => {
  taskData.value.taskRemark = val.selectedOptions[0].text
  showTaskRemark.value = false
}

const snCode = ref<any[]>([])
const showSNPicker = ref(false)
const confirmSN = (val: any) => {
  taskData.value.snCode = val.selectedOptions[0].value
  taskData.value.machineSnCode = val.selectedOptions[0].value
  showSNPicker.value = false
}
</script>

<template>
  <van-nav-bar
    title="跟进反馈"
    left-arrow
    right-text="历史"
    @click-left="onBack"
    @click-right="gotoHistory"
    fixed
    placeholder
  />
  <div class="wrapper">
    <van-cell-group inset v-if="taskData">
      <van-cell title="姓名" :value="taskData.merName" />
      <van-cell title="电话" :value="taskData.merPhone" center clickable>
        <template #value>
          <div class="callPhone">
            <van-icon name="phone" @click="callPhone" class="callIcon" />
            {{ taskData.merPhone }}
          </div>
        </template>
      </van-cell>
      <van-cell title="省市区" :value="taskData.addressHead" />
      <van-cell title="街道" :value="taskData.addressJd" />
    </van-cell-group>

    <van-form @submit="onSubmit" style="margin-top: 16px">
      <van-cell-group inset>
        <van-field
          v-model="taskData.address"
          name="address"
          label="位置"
          :rules="[{ required: true, message: '请输入位置' }]"
        />
        <van-field
          v-model="taskData.taskActiveText"
          name="taskActiveText"
          label="任务状态"
          readonly
          is-link
          @click="showTaskActivePicker = true"
          :rules="[{ required: true, message: '请选择任务状态' }]"
        />
        <van-popup v-model:show="showTaskActivePicker" position="bottom">
          <van-picker
            v-model="taskActive"
            title="选择"
            :columns="[taskActiveList]"
            @cancel="showTaskActivePicker = false"
            @confirm="confirmTaskActive"
          />
        </van-popup>
        <van-field
          v-if="taskData.taskActive == '4'"
          v-model="taskData.isCallText"
          readonly
          :error="taskData.isCall !== '0'"
          name="isCallText"
          label="上门状态"
          disabled
          :rules="[{ required: true, message: '请选择上门状态' }]"
        />
        <van-field
          v-model="taskData.isActiveText"
          readonly
          :disabled="!(taskData.taskActive == '5')"
          name="isActiveText"
          is-link
          label="成交状态"
          @click="isActivePickerShow = true"
        />
        <van-popup v-model:show="isActivePickerShow" position="bottom">
          <van-picker
            v-model="isActive"
            title="选择"
            :columns="[isActiveList]"
            @cancel="isActivePickerShow = false"
            @confirm="confirmIsActive"
          />
        </van-popup>
        <van-field
          v-model="taskData.isUrgentText"
          readonly
          name="isUrgentText"
          disabled
          label="是否加急"
        />
        <van-field
          v-model="taskData.callTime"
          name="callTime"
          v-if="taskData.taskActive == '4'"
          label="上门时间"
          is-link
          readonly
          @click="showTimePicker = true"
          :rules="[{ required: true, message: '请选择上门时间' }]"
        />
        <van-popup v-model:show="showTimePicker" position="bottom">
          <van-picker-group
            title="上门时间"
            :tabs="['选择日期', '选择时间']"
            @confirm="confirmTime"
            @cancel="showTimePicker = false"
          >
            <van-date-picker v-model="currentDate" />
            <van-time-picker v-model="currentTime" />
          </van-picker-group>
        </van-popup>
        <!-- <van-field v-model="taskData.bankName" name="bankName" label="银行名称" /> -->

        <van-field v-model="taskData.remark" name="remark" label="备注" type="textarea" />
        <van-field
          v-if="taskData.taskActive == '5' && taskData.isActive == '2'"
          v-model="taskData.snCode"
          name="snCode"
          readonly
          is-link
          label="机具编号"
          @click="showSNPicker = true"
          :rules="[{ required: true, message: '请输入机具编号' }]"
        />
        <van-popup v-model:show="showSNPicker" position="bottom">
          <van-picker
            v-model="snCode"
            title="选择"
            :columns="[snList]"
            @cancel="showSNPicker = false"
            @confirm="confirmSN"
          />
        </van-popup>
        <van-field
          v-if="taskData.taskActive == '5' && taskData.isActive == '2'"
          v-model="taskData.vehicleName"
          name="snCode"
          label="车主姓名"
          :rules="[{ required: true, message: '请输入车主姓名' }]"
        />
        <van-field
          v-if="taskData.taskActive == '5' && taskData.isActive == '2'"
          v-model="taskData.vehicleNumber"
          name="snCode"
          label="车牌号"
          :rules="[{ required: true, message: '请输入车牌号' }]"
        />
        <van-field
          v-model="taskData.activateTime"
          name="activateTime"
          v-if="taskData.taskActive !== '4'"
          label="下次跟进时间"
          is-link
          readonly
          @click="showActivateTimePicker = true"
          :rules="[{ required: true, message: '请选择下次跟进时间' }]"
        />

        <van-popup v-model:show="showActivateTimePicker" position="bottom">
          <van-date-picker
            title="下次跟进时间"
            v-model="activateTime"
            @confirm="confirmActivateTime"
            @cancel="showActivateTimePicker = false"
          />
        </van-popup>
        <van-field
          v-model="taskData.taskRemark"
          name="remark"
          label="反馈"
          rows="3"
          type="textarea"
          :rules="[{ required: true, message: '请输入反馈内容' }]"
        >
          <template #button v-if="taskData.taskActive == '6'">
            <van-button size="small" type="primary" @click="showTaskRemark = true">
              快速选择
            </van-button>
          </template>
        </van-field>
        <van-popup v-model:show="showTaskRemark" position="bottom">
          <van-picker
            title="选择"
            :columns="[cardTabList]"
            @cancel="showTaskRemark = false"
            @confirm="confirmTaskRemark"
          />
        </van-popup>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="less" scoped>
.wrapper {
  padding: 16px 0;
}
.btnBox {
  padding: 32px 16px;
}
.callIcon {
  color: var(--van-primary-color);
  margin-left: 8px;
  font-size: 21px;
  margin-right: 6px;
}
.callPhone {
  display: flex;
  align-items: center;
  justify-content: end;
}
</style>
